package com.zl.learning.thread.completable_future;

import java.util.Random;
import java.util.concurrent.*;

public class CompletableFutureTest1 {
    private static final Random random = new Random();

    public static void randowDelay() {
        int delay = 500 + random.nextInt(2000);
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void doSomethingElse() {
        System.out.println("doSomethingElse");
    }

    private static Double doSomeLongComputation() {
        randowDelay();
        System.out.println("doSomeLongComputation");
        return 2.2;
    }

    private static Future<Double> getPriceAsync() {
        CompletableFuture<Double> future = new CompletableFuture<Double>();
        new Thread(() -> {
            randowDelay();
            future.complete(2.2);
            System.out.println("bbb");
        }).start();
        return future;
    }

    private static Future<Double> getPriceAsync2() {
        return CompletableFuture.supplyAsync(() -> {
            randowDelay();
            return 2.2;
        });
    }

    public static class Test1 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            ExecutorService executor = Executors.newCachedThreadPool();
            Future<Double> future = executor.submit(CompletableFutureTest1::doSomeLongComputation);
            doSomethingElse();
            Double res = future.get();
            System.out.println(res);
            executor.shutdown();
        }
    }

    public static class Test2 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            Future<Double> future = getPriceAsync();
            System.out.println("ssss");
            System.out.println(future.get());
        }
    }

    public static class Test3 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            Future<Double> future = getPriceAsync2();
            System.out.println("ssss");
            System.out.println(future.get());
        }
    }

    public static class Test4 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            Executor executor = Executors.newCachedThreadPool(r -> {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            });

        }
    }

}
